#include "sparse.h"
#include "check.h"
#include  "main.h"

int check_qc(int matrix[][NB_FAC],	char *dblk, char *pchk, int nb, int z)
{
	int i, j, shift, c=0;
	for (i = 0; i<ParityCheckNum; i++)										
	  pchk[i] = 0;	
	for(i=0; i<ParityCheckNum; i++)
	{
		for(j=0; j<nb; j++)
		{
			if (matrix[i/z][j] >= 0)
			{
				shift = j*z + ((matrix[i/z][j] + i%z) % z);
				pchk[i] ^= dblk[shift];
			}
		}
	}
  for (i = 0; i<ParityCheckNum; i++) 
   c += pchk[i];
  return c;
}

int check
( mod2sparse *H,	
  char *dblk,		
  char *pchk		
)
{ int M, i, c;
  M = mod2sparse_rows(H);
  mod2sparse_mulvec (H, dblk, pchk);
  c = 0;
  for (i = 0; i<M; i++) 
   c += pchk[i];
  return c;
}
/* COUNT HOW MANY BITS HAVED CHANGED FROM BIT INDICATED BY LIKELIHOOD.  The
   simple decoding based on likelihood ratio is compared to the given decoding.
   A bit for which the likelihood ratio is exactly one counts as half a 
   change, which explains why the result is a double rather than an int.
 */
double changed
( double *lratio,
  char *dblk,	
  int N			
)
{ double changed;
  int j;
  changed = 0;
  for (j = 0; j<N; j++)
  { changed += lratio[j]==1 ? 0.5 : dblk[j] != (lratio[j]>1); 
  }
  return changed;
}
/* COMPUTE THE EXPECTED NUMBER OF PARITY CHECK ERRORS.   Computes the
   expected number of parity check errors with respect to the distribution
   given by the bit probabilities passed, with bits assumed to be independent. 
 */
double expected_parity_errors
( mod2sparse *H,	
  double *bpr		
)
{ mod2entry *f;
  double ee, p;
  int M, i, j;
  M = mod2sparse_rows(H);
  ee = 0;
  for (i = 0; i<M; i++)
  { p = 0;
    for (f = mod2sparse_first_in_row(H,i);
         !mod2sparse_at_end(f);
         f = mod2sparse_next_in_row(f))
    { j = mod2sparse_col(f);
      p = p * (1-bpr[j]) + (1-p) * bpr[j];
    }
    ee += p;
  }

  return ee;
}
/* COMPUTE LOG LIKELIHOOD OF A DECODING. */
double loglikelihood 
( double *lratio,
  char *bits,	
  int N			
)
{ double ll;
  int j;
  ll = 0;
  for (j = 0; j<N; j++)
  { ll -= bits[j] ? log(1+1/lratio[j]) : log(1+lratio[j]);
  }
  return ll;
}
/* COMPUTE THE EXPECTED LOG LIKELIHOOD BASED ON BIT PROBABILITIES.  Computes
   the expected value of the log likelihood with respect to the distribution
   given by the bit probabilities passed, with bits assumed to be independent. 
 */
double expected_loglikelihood 
( double *lratio,
  double *bpr,	
  int N			
)
{ double ll;
  int j;
  ll = 0;
  for (j = 0; j<N; j++)
  { if (bpr[j]>0) 
     ll -= bpr[j]*log(1+1/lratio[j]);
    if (bpr[j]<1) 
     ll -= (1-bpr[j])*log(1+lratio[j]);
  }
  return ll;
}
/* COMPUTE ENTROPY FROM BIT PROBABILITIES.  Computes the entropy of the
   distribution given by the bit probabilities, on the assumption that
   bits are independent.
 */
double entropy 
( double *bpr,	
  int N			
)
{ double e;
  int j;
  e = 0;
  for (j = 0; j<N; j++)
  { if (bpr[j]>0 && bpr[j]<1)
     e -= bpr[j]*log(bpr[j]) + (1-bpr[j])*log(1-bpr[j]);
  }
  return e/log(2.0);
}
 